package com.dynamo.transport.network.practise.bio;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @author duanyimiao
 * @create 2018-10-27 9:56 PM
 * @description 客户端，连接服务并发送请求
 **/
public class Client {

    private String host;
    private int port;
    private Socket socket;

    public Client(String host, int port) {
        this.host = host;
        this.port = port;
        socket =  new Socket();
    }

    public void startConnect() throws IOException {
        socket.connect(new InetSocketAddress(host, port));
    }

    public void write(String msg) throws IOException {
        socket.getOutputStream().write(msg.getBytes());
    }

    public void read() throws IOException {

        InputStream in = socket.getInputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] bytes = new byte[4096];
        int n = -1;
        //如果没有数据可以读，线程一直阻塞在read方法上
        while(-1 != ( n = in.read(bytes))){
            bos.write(bytes,0,n);
            System.out.println("rece server msg="+new String(bos.toByteArray()));
            bos.reset();
        }
    }

}
